package me.heizi.springboot.students.services

import me.heizi.springboot.students.controllers.dto.UserDTO
import me.heizi.springboot.students.entities.User
import me.heizi.springboot.students.repositories.UserRepository
import me.heizi.springboot.students.updateNotNull
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.lang.IllegalArgumentException
import java.util.logging.Level
import java.util.logging.Logger


@Service
class UserService(
    @Autowired private val repository: UserRepository
) {
    fun User.toUserUpdateDTO(): UserDTO = UserDTO(
        password = password,
        phone = phone,
        remark = remark,
        classId = classId
    )

    val all get() = repository.selectList(null)


    fun updateByName(username:String,body: UserDTO) = repository.selectByName(username)?.let { user->
        val dto = user.toUserUpdateDTO()
        dto.updateNotNull(body)
        val user = dto.toUser(user)
        repository.updateById(user)
    } ?: throw IllegalArgumentException()

    fun delete(id: Int) = repository
        .selectList(null)
        .filter {
            it.id == id
        }.map {
            repository.runCatching {
                deleteById(it.id)
            }.onFailure {
                Logger.getLogger(repository.javaClass.name)
                    .log(Level.WARNING, it.message, it)
            }.isSuccess
        }

    fun update(user: User) = repository.updateById(user) == 0
}